﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;


namespace CsFileFormatterAndStatistics
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void BtnSelectFile_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;

                try
                {
                    // 读取文件所有行
                    var allLines = File.ReadAllLines(filePath);

                    // 统计原始行数
                    int originalLineCount = allLines.Length;

                    // 统计原始单词数
                    int originalWordCount = CountWords(allLines);

                    // 更新UI
                    lblOriginalLines.Text = $"原始行数: {originalLineCount}";
                    lblOriginalWords.Text = $"原始单词数: {originalWordCount}";

                    // 格式化文件: 删除空行和以//开头的注释行
                    var formattedLines = allLines
                        .Where(line => !IsEmptyLine(line) && !IsCommentLine(line))
                        .ToList();

                    // 统计格式化后的行数
                    int formattedLineCount = formattedLines.Count;

                    // 统计格式化后的单词数
                    int formattedWordCount = CountWords(formattedLines);

                    // 更新UI
                    lblFormattedLines.Text = $"格式化行数: {formattedLineCount}";
                    lblFormattedWords.Text = $"格式化单词数: {formattedWordCount}";

                    // 统计单词出现次数
                    var wordCounts = GetWordCounts(formattedLines);

                    // 显示单词统计结果
                    DisplayWordCounts(wordCounts);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"处理文件时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 判断一行是否为空行
        /// </summary>
        private bool IsEmptyLine(string line)
        {
            return string.IsNullOrWhiteSpace(line);
        }

        /// <summary>
        /// 判断一行是否是以//开头的注释行
        /// </summary>
        private bool IsCommentLine(string line)
        {
            string trimmed = line.TrimStart();
            return trimmed.StartsWith("//");
        }

        /// <summary>
        /// 统计单词数（不包括空格、空行及标点符号）
        /// </summary>
        private int CountWords(IEnumerable<string> lines)
        {
            int count = 0;
            foreach (var line in lines)
            {
                var words = ExtractWords(line);
                count += words.Count;
            }
            return count;
        }

        /// <summary>
        /// 提取一行中的单词（不包括标点符号）
        /// </summary>
        private List<string> ExtractWords(string line)
        {
            // 使用正则表达式匹配单词（字母、数字和下划线）
            var matches = Regex.Matches(line, @"\b\w+\b");
            return matches.Cast<Match>().Select(m => m.Value).ToList();
        }

        /// <summary>
        /// 统计每个单词出现的次数（不区分大小写）
        /// </summary>
        private Dictionary<string, int> GetWordCounts(IEnumerable<string> lines)
        {
            Dictionary<string, int> wordCounts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

            foreach (var line in lines)
            {
                var words = ExtractWords(line);
                foreach (var word in words)
                {
                    string lowerWord = word.ToLower();
                    if (wordCounts.ContainsKey(lowerWord))
                    {
                        wordCounts[lowerWord]++;
                    }
                    else
                    {
                        wordCounts[lowerWord] = 1;
                    }
                }
            }

            // 按照出现次数降序排序
            return wordCounts.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key).ToDictionary(kv => kv.Key, kv => kv.Value);
        }

        /// <summary>
        /// 在DataGridView中显示单词统计结果
        /// </summary>
        private void DisplayWordCounts(Dictionary<string, int> wordCounts)
        {
            dgvWordCounts.Columns.Clear();
            dgvWordCounts.Rows.Clear();

            dgvWordCounts.Columns.Add("Word", "单词");
            dgvWordCounts.Columns.Add("Count", "出现次数");

            foreach (var kv in wordCounts)
            {
                dgvWordCounts.Rows.Add(kv.Key, kv.Value);
            }

            // 设置列宽自适应
            dgvWordCounts.AutoResizeColumns();
        }
    }
}
